package org.xiaoyu.feign.core;

import java.io.IOException;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;


public class ZookeeperService {

	public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
	      //创建ZooKeeper实例
        ZooKeeper zk = new ZooKeeper("172.16.40.130:2181", 100, new Wa());
        
        String path = "/feignService";
        Stat stat = zk.exists(path, new Wa());
        if(stat == null) {
            zk.create(path, "ROOT".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
        String servicePath = path + "/testApi";
        if(zk.exists(servicePath, null) == null) {
       		zk.create(servicePath, "2".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
        zk.getChildren(servicePath, new Watcher() {
			@Override
			public void process(WatchedEvent event) {
				System.out.println(event.getPath());
				System.out.println(event.getType());
				System.out.println(event.getState());
				try {
					zk.getChildren(servicePath, this);
				} catch (KeeperException | InterruptedException e) {
				
					e.printStackTrace();
				}
			}
		});
        zk.create(servicePath + "/172.24.38.193:8084", "2".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
//   		zk.delete(path + "/service1", -1);  
//       	byte[] data = zk.getData(path, new Wa(), null);
//       	System.out.println(new String(data));
       	zk.close();
 
	}
	
	
	static class Wa implements Watcher{
		@Override
		public void process(WatchedEvent event) {
			System.out.println(event.getPath());
			System.out.println(event.getType());
			System.out.println(event.getState());
			
		}
	}


}
